package org.thanos.demo.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.thanos.demo.mapper.DemoMapper;
import org.thanos.demo.model.Demo;
import org.thanos.demo.model.PageResult;
import org.thanos.demo.vo.DemoVO;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
public class DemoController {

    private static final Logger LOGGER = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    private DemoMapper demoMapper;

    @PutMapping("/demo")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    public void updateDemo(@RequestBody DemoVO demoVO) {
        Demo demo = demoMapper.selectById(demoVO.getId());
        demo.setName(demoVO.getName());
        demoMapper.updateById(demo);
    }

    @PostMapping("/demo")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    public void insertDemo(@RequestBody DemoVO demoVO) {
        Demo demo = new Demo();
        demo.setName(demoVO.getName());
        demoMapper.insert(demo);
    }

    @GetMapping("/demo")
    public DemoVO queryOne(@RequestParam("id") Integer id) {
        Demo demo = demoMapper.selectById(id);
        List<Demo> demos = demoMapper.selectByIds(Collections.singletonList(id));
        LOGGER.info(demos.toString());
        if (!Optional.ofNullable(demo).isPresent()) {
            return null;
        }
        return DemoVO.convertToDemoVO(demo);
    }

    @GetMapping("/demos")
    public PageResult<DemoVO> queryAll(@RequestParam("pageNum") int pageNum, @RequestParam("pageSize") int pageSize) {
        Page<Demo> page = PageHelper.startPage(pageNum, pageSize, true);
        demoMapper.selectAll();
        PageInfo<Demo> info = PageInfo.of(page.getResult());
        if (CollectionUtils.isEmpty(info.getList())) {
            return PageResult.of(0, Collections.emptyList());
        }
        return PageResult.of(info.getTotal(), info.getList().stream().map(demo -> {
            DemoVO result = new DemoVO();
            result.setId(demo.getId());
            result.setName(demo.getName());
            return result;
        }).collect(Collectors.toList()));
    }

    @DeleteMapping("/demo")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)
    public void deleteDemo(@RequestParam("id") Integer id) {
        demoMapper.deleteById(id);
    }
}
